package com.example.netty.nio.reactor.masterslave;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * NIO 服务端 基于Reactor模型的主从模型
 *
 * @author LSQ
 * @since 2023/2/19 10:04
 */
public class Server {

    public static void main(String[] args) {
        try {
            ServerSocketChannel channel = ServerSocketChannel.open();
            channel.configureBlocking(false);
            channel.bind(new InetSocketAddress(8888));
            Selector selector = Selector.open();
            channel.register(selector, SelectionKey.OP_ACCEPT);

            // 用来处理客户端连接的线程池
            ExecutorService bossExecutorService = Executors.newFixedThreadPool(5);
            // 用来处理IO操作的线程池
            ExecutorService workerExecutorService = Executors.newFixedThreadPool(10);

            while (selector.select() > 0) {
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();

                    if (selectionKey.isAcceptable()) {

                        bossExecutorService.execute(() -> {
                            try {
                                // 处理客户端的连接
                                System.out.println(Thread.currentThread().getName() + " ---> 开始处理客户端的连接请求...");
                                SocketChannel socketChannel = channel.accept();
                                socketChannel.configureBlocking(false);
                                socketChannel.register(selector, SelectionKey.OP_READ);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        });

                    } else if (selectionKey.isReadable()) {

                        workerExecutorService.execute(() -> {
                            // 处理IO操作...
                        });

                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
